package com.kly.user.task.v2;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.user.db.dao.UserDailyActivityDao;
import com.kly.user.db.dao.UserDao;
import com.kly.user.db.entity.UserDailyActivityEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 统计用户活跃情况
 */
@Service
public class ActiveUserTask {

    private static Log logger = LogFactory.getLog(ActiveUserTask.class);

    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;
    @NacosValue(value = "${enable.active.user.switch:true}", autoRefreshed = true)
    private Boolean enableFlashChatSwitch;
    private String localIP = NetUtil.getLocalhostStr();
    @Resource
    UserDailyActivityDao userDailyActivityDao;

    /**
     * 执行频率：10分钟
     */
    @Scheduled(fixedDelay = 60000 * 10)
    public void run() {
        logger.info("====ActiveUserTask start");
        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============ActiveUserTask, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }
        if (!enableFlashChatSwitch) {
            logger.info("=============ActiveUserTask, enableFlashchatSwitch:{}", enableFlashChatSwitch);
            return;
        }

        int todayDate = Integer.parseInt(DateUtil.format(new Date(), "yyyyMMdd"));
        Integer newUserDailyActiveToday = userDailyActivityDao.getNewUserDailyActiveToday();
        Integer oldUserDailyActiveToday = userDailyActivityDao.getOldUserDailyActiveToday();
        UserDailyActivityEntity userDailyActiveData = userDailyActivityDao.getUserDailyActiveData(todayDate);
        if (userDailyActiveData == null) {
            userDailyActiveData = new UserDailyActivityEntity();
            userDailyActiveData.setOnDate(todayDate);
            userDailyActiveData.setNewCount(newUserDailyActiveToday);
            userDailyActiveData.setOldCount(oldUserDailyActiveToday);
            userDailyActiveData.setTotalCount(newUserDailyActiveToday + oldUserDailyActiveToday);
            userDailyActivityDao.insert(userDailyActiveData);
        } else {
            userDailyActiveData.setNewCount(newUserDailyActiveToday);
            userDailyActiveData.setOldCount(oldUserDailyActiveToday);
            userDailyActiveData.setTotalCount(newUserDailyActiveToday + oldUserDailyActiveToday);
            userDailyActivityDao.updateByPrimaryKey(userDailyActiveData);
        }
    }

}